package ru.niir.goodfil.ui.audit;

import ru.niir.goodfil.audit.domain.Event;
import ru.niir.goodfil.db.audit.helpers.AuditHelper;
import ru.niir.goodfil.ui.SecurityBean;
import ru.niir.goodfil.ui.utils.FacesUtils;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

/**
 * @author ksazonov
 */
public class JsfAuditHelper implements AuditHelper {
    public String getIp() {
        String ip = "undefined";
        try {
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            ip = request.getRemoteAddr();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

    public String getLogin() {
        String login = "undefined";

        try {
            SecurityBean securityBean = FacesUtils.getManagedBean("SecurityBean");
            login = securityBean.getCurrentUser().getLogin();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return login;
    }

    @Override
    public <T extends Event> T createEvent(Class<? extends Event> klass) {
        try {
            Event event = klass.newInstance();

            event.setIp(getIp());
            event.setLogin(getLogin());

            return (T) event;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
